<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>用户管理</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/layui/css/layui.css">
    <script src="${pageContext.request.contextPath}/static/layui/layui.js"></script>
    <script src="${pageContext.request.contextPath}/static/jquery-3.5.1.min.js"></script>
    <script src="${pageContext.request.contextPath}/static/layui/xm-select.js"></script>
    <style>
        *{
            padding: 0px;
        }
        .layui-table-cell{
            text-align:center;
            height: auto;
            white-space: normal;
        }
        .layui-form-select dl { max-height:100px; }
    </style>
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
    <legend><span style="font-size: xx-large;font-weight: bold;"> 用户管理</span></legend>
</fieldset>
<div class="layui-container">
    <div>
        <form class="layui-form" action="">
            <div class="layui-row layui-col-space30">
                <div class="layui-col-md3">
                    <input class="layui-input" name="" id="search-username" autocomplete="off"  placeholder="请输入用户名">
                </div>
                <div class="layui-col-md3">
                    <input class="layui-input" name="" id="search-account" autocomplete="off"  placeholder="请输入账号">
                </div>
                <div class="layui-col-md3">
                    <input class="layui-input" name="" id="search-phone" autocomplete="off"  placeholder="请输入手机号">
                </div>
                <div class="layui-col-md2">
                    <div id="search-sex" class="xm-select-demo"></div>
                </div>
                <div class="layui-col-md3">
                    <div id="search-role" class="xm-select-demo"></div>
                </div>
                <div class="layui-col-md3 layui-col-md-offset6">
                    <button id="searchBtn" type="button" class="layui-btn" lay-filter="formDemo">搜索</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>
    <div class="layui-row">
        <table class="layui-hide" id="userTable" lay-skin="line" lay-filter="userTable">
        </table>
    </div>
</div>

<script type="text/html" id="toolbar">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-danger" lay-event="deleteUsers">删除选中行</button>
        <button class="layui-btn layui-btn-normal" lay-event="saveUser">新增</button>
    </div>
</script>
<script type="text/html" id="bar">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a><br/>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
</script>
<script>
    var searchSex = xmSelect.render({
        el: '#search-sex',
        tips: '性别',
        data: [
            <c:forEach items="${applicationScope.sexList}" var="a">
            {name: '${a.value}',value: '${a.orderNo}', selected: true},
            </c:forEach>
        ]
    })
    var searchRole = xmSelect.render({
        el: '#search-role',
        tips: '角色',
        data: [
            <c:forEach items="${applicationScope.roleList}" var="a">
            {name: '${a.value}',value: '${a.orderNo}', selected: true},
            </c:forEach>
        ]
    })
    layui.use(['table','form'], function(){
        var table = layui.table;
        var form = layui.form;

        $("#searchBtn").click(function (){
            reload();
        })

        var tableIns = table.render({
            elem: '#userTable'
            ,url:'${pageContext.request.contextPath}/user/getUsersByCondition.do'
            ,toolbar: '#toolbar'
            ,where: {
                "username": $('#search-username').val(),
                "account": $('#search-account').val(),
                "phone": $('#search-phone').val(),
                "sex": searchSex.getValue('name'),
                "role": searchRole.getValue('name')
            }
            ,defaultToolbar: []
            ,page: true
            ,limits: [5,10,20]
            ,limit: 10
            ,parseData: function(res){
                var result;
                if(this.page.curr){
                    result = res.data.slice(this.limit*(this.page.curr-1),this.limit*this.page.curr);
                }
                else{
                    result=res.data.slice(0,this.limit);
                }
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.count,
                    "data": result
                };
            }
            ,cols: [[
                {type:'checkbox',fixed: 'left'}
                ,{field:'id',title: 'ID',hide: true}
                ,{field:'username',width: 150, title: '用户名'}
                ,{field:'account',width: 150, title: '账号'}
                ,{field:'sex',width: 100, title: '性别'}
                ,{field:'phone',width: 150, title: '手机号码'}
                ,{field:'role',width: 100, title: '角色'}
                ,{field:'borrowBookLimit',width: 100,title: '可借图书数'}
                ,{field:'borrowBooks',width: 100,title: '已借图书数'}
                ,{field:'borrowTimeLimit',width: 100, title: '每次次可借时间'}
                ,{title: '操作',fixed: 'right',width: 100, toolbar: '#bar'}
            ]]
            ,done: function (res, curr, count) {//动态监听表头高度变化，冻结行跟着改变高度
                $(".layui-table-header  tr").resize(function () {
                    $(".layui-table-header  tr").each(function (index, val) {
                        $($(".layui-table-fixed .layui-table-header table tr")[index]).height($(val).height());
                    });
                });
                //初始化高度，使得冻结行表头高度一致
                $(".layui-table-header  tr").each(function (index, val) {
                    $($(".layui-table-fixed .layui-table-header table tr")[index]).height($(val).height());
                });
                //动态监听表体高度变化，冻结行跟着改变高度
                $(".layui-table-body  tr").resize(function () {
                    $(".layui-table-body  tr").each(function (index, val) {
                        $($(".layui-table-fixed .layui-table-body table tr")[index]).height($(val).height());
                    });
                });
                //初始化高度，使得冻结行表体高度一致
                $(".layui-table-body  tr").each(function (index, val) {
                    $($(".layui-table-fixed .layui-table-body table tr")[index]).height($(val).height());
                });
            }
        });
        //定义输入规则
        var reNumber = /^[0-9]\d*$/;
        var rePhone = /^(13\d|14[579]|15[^4\D]|17[^49\D]|18\d)\d{8}$/;

        //监听工具条
        table.on('tool(userTable)', function(obj){
            var data = obj.data;
            switch(obj.event){
                case 'delete':
                    layer.confirm('真的删除么', function(index){
                        $.ajax({
                            url:"${pageContext.request.contextPath}/user/deleteUserById.do",
                            data:{
                                "id" : data.id
                            },
                            type:"post",
                            dataType:"json",
                            success:function (n){
                                if(n.success){
                                    reload();
                                }else {
                                    layer.msg("删除账号为"+data.account+"的用户失败,"+n.msg);
                                }
                            }
                        });
                        layer.close(index);
                    });
                    break;
                case 'edit':
                    layer.open({
                        type: 1,
                        area: ['800px', '460px'],
                        shadeClose: true, //点击遮罩关闭
                        title: '修改用户',
                        btn: ['确定', '取消'],
                        content: $('#editUserFrame'),
                        success: function (index, layero){
                            $("#edit-account").val(data.account);
                            $("#edit-account").attr("disabled","disabled");
                            $("#edit-password").val("");
                            $("#edit-username").val(data.username);
                            $("#edit-phone").val(data.phone);
                            $("#edit-role").val(data.role);
                            $("#edit-sex").val(data.sex);
                            if(data.role !== '用户'){
                                $("#edit-borrowBookLimit").attr("class","layui-input layui-disabled");
                                $("#edit-borrowBookLimit").attr("disabled","disabled");
                                $("#edit-borrowBookLimit").val("0");
                                $("#edit-borrowTimeLimit").attr("class","layui-input layui-disabled");
                                $("#edit-borrowTimeLimit").attr("disabled","disabled");
                                $("#edit-borrowTimeLimit").val("0");
                            }else {
                                $("#edit-borrowBookLimit").attr("class","layui-input");
                                $("#edit-borrowBookLimit").removeAttr("disabled","disabled");
                                $("#edit-borrowBookLimit").val(data.borrowBookLimit);
                                $("#edit-borrowTimeLimit").attr("class","layui-input");
                                $("#edit-borrowTimeLimit").removeAttr("disabled","disabled");
                                $("#edit-borrowTimeLimit").val(data.borrowTimeLimit);
                            }
                            form.render();
                        },
                        yes: function (index, layero){
                            var password = $.trim($("#edit-password").val());
                            var username = $.trim($("#edit-username").val());
                            var phone = $.trim($("#edit-phone").val());
                            var role = $.trim($("#edit-role").val());
                            var sex = $.trim($("#edit-sex").val());
                            var borrowBookLimit = $.trim($("#edit-borrowBookLimit").val());
                            var borrowTimeLimit = $.trim($("#edit-borrowTimeLimit").val());
                            if(password===''){
                                layer.msg("请输入密码");
                                return false;
                            }
                            if(username===''){
                                layer.msg("请输入用户名");
                                return false;
                            }
                            if(!(rePhone.test(phone))){
                                layer.msg("请输入正确的手机号码");
                                return false;
                            }
                            if(!reNumber.test(borrowBookLimit)){
                                layer.msg("请输入正确的可借图书数");
                                return false;
                            }
                            if(!reNumber.test(borrowTimeLimit)){
                                layer.msg("请输入正确的可借天数");
                                return false;
                            }
                            $.ajax({
                                url:"${pageContext.request.contextPath}/user/updateUser.do",
                                data:{
                                    "id" : data.id,
                                    "account" : data.account ,
                                    "username" : username ,
                                    "password" : password ,
                                    "role" : role ,
                                    "sex" : sex ,
                                    "phone" : phone ,
                                    "borrowBookLimit" : borrowBookLimit ,
                                    "borrowTimeLimit" :  borrowTimeLimit
                                },
                                type:"post",
                                dataType:"json",
                                success:function (n){
                                    if(n.success){
                                        layer.msg("更新账号为"+data.account+"的用户成功");
                                        reload();
                                        layer.close(index);
                                    }else {
                                        layer.msg("更新账号为"+data.account+"的用户失败");
                                    }
                                }
                            });
                        },
                        end: function (res) {
                            $("#editUserFrame").css("display",'none');
                        }
                    });
                    break;
            };
        });
        table.on('toolbar(userTable)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'deleteUsers':
                    var data = checkStatus.data;
                    var size = data.length;
                    console.log(data);
                    if(size != 0){
                        layer.confirm('真的删除么', function(index){
                            for(let i = 0; i < size; i++){
                                $.ajax({
                                    url:"${pageContext.request.contextPath}/user/deleteUserById.do",
                                    data:{
                                        "id" : data[i].id
                                    },
                                    async:false,
                                    type:"post",
                                    dataType:"json",
                                    success:function (n){
                                        if(!n.success){
                                            layer.msg("删除账号为"+data[i].account+"的用户失败,"+n.msg);
                                        }
                                    }
                                });
                            }
                            layer.close(index);
                            reload();
                        });
                    }else {
                        layer.msg("请勾选要删除的用户");
                    }
                    break;
                case 'saveUser':
                    layer.open({
                        type: 1,
                        area: ['800px', '460px'],
                        shadeClose: true, //点击遮罩关闭
                        title: '添加用户',
                        btn: ['确定', '取消'],
                        content: $('#saveUserFrame'),
                        success: function (index, layero){
                            $("#save-account").val("");
                            $("#save-password").val("");
                            $("#save-username").val("");
                            $("#save-phone").val("");
                            $("#save-role").val("用户");
                            $("#save-sex").val("男");
                            $("#save-borrowBookLimit").val("");
                            $("#save-borrowTimeLimit").val("");
                            form.render();
                        },
                        yes: function (index, layero){
                            var account = $.trim($("#save-account").val());
                            var password = $.trim($("#save-password").val());
                            var username = $.trim($("#save-username").val());
                            var phone = $.trim($("#save-phone").val());
                            var role = $.trim($("#save-role").val());
                            var sex = $.trim($("#save-sex").val());
                            var borrowBookLimit = $.trim($("#save-borrowBookLimit").val());
                            var borrowTimeLimit = $.trim($("#save-borrowTimeLimit").val());
                            if(account===''){
                                layer.msg("请输入账号");
                                return false;
                            }
                            if(password===''){
                                layer.msg("请输入密码");
                                return false;
                            }
                            if(username===''){
                                layer.msg("请输入用户名");
                                return false;
                            }
                            if(!(rePhone.test(phone))){
                                layer.msg("请输入正确的手机号码");
                                return false;
                            }
                            if(!reNumber.test(borrowBookLimit)){
                                layer.msg("请输入正确的可借图书数");
                                return false;
                            }
                            if(!reNumber.test(borrowTimeLimit)){
                                layer.msg("请输入正确的可借天数");
                                return false;
                            }
                            $.ajax({
                                url:"${pageContext.request.contextPath}/user/saveUser.do",
                                data:{
                                    "account" : account ,
                                    "username" : username ,
                                    "password" : password ,
                                    "role" : role ,
                                    "sex" : sex ,
                                    "phone" : phone ,
                                    "borrowBookLimit" : borrowBookLimit ,
                                    "borrowTimeLimit" :  borrowTimeLimit
                                },
                                type:"post",
                                dataType:"json",
                                success:function (n){
                                    if(n.success){
                                        layer.msg("添加账号为"+account+"的用户成功");
                                        reload();
                                        layer.close(index);
                                    }else {
                                        layer.msg("添加账号为"+account+"的用户失败,"+n.msg);
                                    }
                                }
                            });
                        },
                        end: function (res) {
                            $("#saveUserFrame").css("display",'none');
                        }
                    });
                    break;
            };
        });
        form.on('select(saveRole)', function(data){
            console.log(data.value);
            if(data.value !== '用户'){
                $("#save-borrowBookLimit").attr("class","layui-input layui-disabled");
                $("#save-borrowBookLimit").attr("disabled","disabled");
                $("#save-borrowBookLimit").val("0");
                $("#save-borrowTimeLimit").attr("class","layui-input layui-disabled");
                $("#save-borrowTimeLimit").attr("disabled","disabled");
                $("#save-borrowTimeLimit").val("0");
            }else {
                $("#save-borrowBookLimit").attr("class","layui-input");
                $("#save-borrowBookLimit").removeAttr("disabled","disabled");
                $("#save-borrowBookLimit").val("");
                $("#save-borrowTimeLimit").attr("class","layui-input");
                $("#save-borrowTimeLimit").removeAttr("disabled","disabled");
                $("#save-borrowTimeLimit").val("");
            }
        });
        form.on('select(editRole)', function(data){
            console.log(data.value);
            if(data.value !== '用户'){
                $("#edit-borrowBookLimit").attr("class","layui-input layui-disabled");
                $("#edit-borrowBookLimit").attr("disabled","disabled");
                $("#edit-borrowBookLimit").val("0");
                $("#edit-borrowTimeLimit").attr("class","layui-input layui-disabled");
                $("#edit-borrowTimeLimit").attr("disabled","disabled");
                $("#edit-borrowTimeLimit").val("0");
            }else {
                $("#edit-borrowBookLimit").attr("class","layui-input");
                $("#edit-borrowBookLimit").removeAttr("disabled","disabled");
                $("#edit-borrowBookLimit").val("");
                $("#edit-borrowTimeLimit").attr("class","layui-input");
                $("#edit-borrowTimeLimit").removeAttr("disabled","disabled");
                $("#edit-borrowTimeLimit").val("");
            }
        });
        function reload(){
            tableIns.reload({
                where: {
                    "username": $('#search-username').val(),
                    "account": $('#search-account').val(),
                    "phone": $('#search-phone').val(),
                    "sex": searchSex.getValue('name'),
                    "role": searchRole.getValue('name')
                }
                ,page: {
                    curr: 1
                }
            });
        }
    });
</script>
</body>
<div style="display:none;" id="saveUserFrame">
    <div class="layui-form layui-form-pane" style="width: 90%;padding: 30px;">
        <div class="layui-form-item">
            <label class="layui-form-label">账号</label>
            <div class="layui-input-block">
                <input class="layui-input" id="save-account" autocomplete="off"  placeholder="请输入登录账号">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">密码</label>
            <div class="layui-input-block">
                <input class="layui-input" id="save-password" autocomplete="off"  placeholder="请输入密码">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="save-username" autocomplete="off"  placeholder="请输入用户名">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">性别</label>
                <div class="layui-input-inline">
                    <select id="save-sex">
                        <c:forEach items="${applicationScope.sexList}" var="a">
                            <option value="${a.value}">${a.value}</option>
                        </c:forEach>
                    </select>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">手机号码</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="save-phone" autocomplete="off"  placeholder="请输入手机号">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">角色</label>
                <div class="layui-input-inline">
                    <select id="save-role" lay-filter="saveRole">
                        <c:forEach items="${applicationScope.roleList}" var="a">
                            <option value="${a.value}">${a.value}</option>
                        </c:forEach>
                    </select>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label" style="width:175px;">可借图书数量</label>
                <div class="layui-input-inline" style="width:125px;">
                    <input class="layui-input" id="save-borrowBookLimit" autocomplete="off"  placeholder="可借图书数量">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width:175px;">一次可借天数</label>
                <div class="layui-input-inline" style="width:125px;">
                    <input class="layui-input" id="save-borrowTimeLimit" autocomplete="off"  placeholder="可借阅天数">
                </div>
            </div>
        </div>
    </div>
</div>
<div style="display:none;" id="editUserFrame">
    <div class="layui-form layui-form-pane" style="width: 90%;padding: 30px;">
        <div class="layui-form-item">
            <label class="layui-form-label">账号</label>
            <div class="layui-input-block">
                <input class="layui-input" id="edit-account" autocomplete="off"  placeholder="请输入登录账号">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">密码</label>
            <div class="layui-input-block">
                <input class="layui-input" id="edit-password" autocomplete="off"  placeholder="请输入密码">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="edit-username" autocomplete="off"  placeholder="请输入用户名">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">性别</label>
                <div class="layui-input-inline">
                    <select id="edit-sex">
                        <c:forEach items="${applicationScope.sexList}" var="a">
                            <option value="${a.value}">${a.value}</option>
                        </c:forEach>
                    </select>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">手机号码</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="edit-phone" autocomplete="off"  placeholder="请输入手机号">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">角色</label>
                <div class="layui-input-inline">
                    <select id="edit-role" lay-filter="editRole">
                        <c:forEach items="${applicationScope.roleList}" var="a">
                            <option value="${a.value}">${a.value}</option>
                        </c:forEach>
                    </select>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label" style="width:175px;">可借图书数量</label>
                <div class="layui-input-inline" style="width:125px;">
                    <input class="layui-input" id="edit-borrowBookLimit" autocomplete="off"  placeholder="可借图书数量">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width:175px;">一次可借天数</label>
                <div class="layui-input-inline" style="width:125px;">
                    <input class="layui-input" id="edit-borrowTimeLimit" autocomplete="off"  placeholder="可借阅天数">
                </div>
            </div>
        </div>
    </div>
</div>
</html>